package com.dsteiner.xelavos.server;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.dsteiner.xelavos.client.domain.User;

public interface EmailUtil {

	public static class EmailUtilImpl implements EmailUtil{
		private static EmailUtil instance;
		
		public static EmailUtil getInstance(){
			if(instance == null)
				instance = new EmailUtilImpl();
			return instance;
		}
		
		private EmailUtilImpl() {
		}
		
		public void doSendEmail(String subject, String email, String plainText, String htmlText) {
			doSendEmail(subject, email, email, plainText, htmlText);
		}
		
		public void doSendEmail(String subject, String email, String personal, String plainText, String htmlText) {
			try{
				Properties props = new Properties();
			    Session session = Session.getDefaultInstance(props, null);
			    
			    Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress("Dominik.J.Steiner@googlemail.com", "XelaVos.com reportes"));
			    msg.addRecipient(Message.RecipientType.TO,
			                     new InternetAddress(email, personal));
				msg.setSubject(subject);
			    
			    Multipart multipart = new MimeMultipart("alternative");
				
				BodyPart plainMessageBodyPart = new MimeBodyPart();
				plainMessageBodyPart.setContent(plainText,"text/plain");
				
				multipart.addBodyPart(plainMessageBodyPart);
		
				BodyPart htmlMessageBodyPart = new MimeBodyPart();
				htmlMessageBodyPart.setContent(htmlText, "text/html");
				
				multipart.addBodyPart(htmlMessageBodyPart);
				
				msg.setContent(multipart);
				Transport.send(msg);
			} catch(Exception ex){
				ex.printStackTrace();
			}
			
		}
		
		public void doSendEmail(String subject, User user, String plainText, String htmlText) {
			doSendEmail(subject, user.getEmail(), user.getFirstName() + " " + user.getLastName(), plainText, htmlText);
		}
		
	}
	
	public void doSendEmail(String subject, String email, String plainText, String htmlText);

	void doSendEmail(String subject, String email, String personal, String plainText, String htmlText);

	public void doSendEmail(String subject, User user, String plainText, String htmlText);

}
